package com.btr.ivle.backgroud;

import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;

import com.btr.ivle.R;
import com.btr.ivle.data.ForumData;
import com.btr.ivle.data.IVLEToken;
import com.btr.ivle.helper.MapComparator;
import com.btr.ivle.helper.URLtoString;

public class GetForumThreadTask extends AsyncTask<String, Void, Void>{
	
	private Context context;
	
	public GetForumThreadTask(Context context){
		this.context = context;
	}

	protected Void doInBackground(String... texts) {
		String ThreadID = texts[0];
		
		try{
        	URL url = new URL("https://ivle.nus.edu.sg/api/Lapi.svc/Forum_Threads?APIKey=" +
        			context.getString(R.string.IVLE_API_KEY) + "&AuthToken=" + IVLEToken.getToken() + "&ThreadID="
        				+ ThreadID + "&Duration=0&GetSubThreads=true");
        	JSONObject jObject = new JSONObject(URLtoString.get(url));
	        JSONArray resultsArrary = jObject.getJSONArray("Results");
	        List<Map<String, String>> listThread = new ArrayList<Map<String, String>>();
	        Comparator<Map<String, String>> mapComparator = new MapComparator("PostDate", true);
	        
	        listThread.addAll(getThread(resultsArrary));
	        Collections.sort(listThread, mapComparator);
	        ForumData.add(ThreadID, listThread);
	        
		}catch(JSONException ex){
        	Log.e("JSONException", ex.getMessage());
	    }catch(Exception ex){
        	//Log.e("Exception", ex.getMessage());
	    }
		Log.i("test","return");
		return null;
	}
	
	private List<Map<String, String>> getThread(JSONArray threads) throws Exception{
		List<Map<String, String>> list = new ArrayList<Map<String, String>>();
		Map<String, String> map;
		String ID;
		for(int i = 0; i < threads.length(); i++){
    		map = new HashMap<String, String>();
    		ID = threads.getJSONObject(i).getString("ID").toString();
    		map.put("ID", ID);
    		map.put("PostTitle", threads.getJSONObject(i).getString("PostTitle").toString());
    		map.put("PostBody", threads.getJSONObject(i).getString("PostBody").toString().toString());
    		map.put("PostDate", threads.getJSONObject(i).getString("PostDate").toString().substring(6, 19));
    		map.put("PosterName", threads.getJSONObject(i).getJSONObject("Poster").getString("Name").toString());
    		map.put("PosterEmail", threads.getJSONObject(i).getJSONObject("Poster").getString("Email").toString());
    		if(threads.getJSONObject(i).getBoolean("isPosterStaff")){
    			map.put("isPosterStaff", null);
    		}
    		list.add(map);
    		
    		JSONArray childThreads = threads.getJSONObject(i).getJSONArray("Threads");
    		if(childThreads.length()>0)
    			list.addAll(getThread(childThreads));
    		
    		HttpClient httpclient = new DefaultHttpClient();
        	HttpPost httppost = new HttpPost("https://ivle.nus.edu.sg/api/Lapi.svc/Forum_Thread_AddLog_JSON");
        	List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
        	nameValuePairs.add(new BasicNameValuePair("APIKey", context.getString(R.string.IVLE_API_KEY)));
            nameValuePairs.add(new BasicNameValuePair("AuthToken", IVLEToken.getToken()));
            nameValuePairs.add(new BasicNameValuePair("ThreadID", ID));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs,HTTP.UTF_8));
            httpclient.execute(httppost);
    	}
		return list;
	}
	
	@SuppressWarnings("unchecked")
    protected void onPostExecute(Void result) {	
		AsyncTaskCompleteListener<String> l = (AsyncTaskCompleteListener<String>) context;
    	l.onAsyncTaskComplete(""); 
    }
}
